package com.controller;

import com.constants.SessionKey;
import com.dto.excution.LoginExcution;
import com.entity.LoginInfo;
import com.enums.LoginEnum;
import com.service.BillService;
import com.service.LoginService;
import com.util.UUIDUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/18 0018.
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private BillService billService;

    @ApiOperation(value = "手机号密码登陆")
    @PostMapping(value = "/login")
    @ResponseBody
    public LoginExcution<LoginInfo> login(HttpServletRequest request, String phone, String password, Integer type, Integer pid) {
        LoginInfo loginInfo = loginService.findPhone(phone, MD5(password), type);
        if (loginInfo == null) {
            return new LoginExcution<LoginInfo>(null, LoginEnum.STAFF_ACCOUNT_NOT_EXIST);
        }
        if (loginInfo.getStatus().equals("NO")) {
            return new LoginExcution<LoginInfo>(null, LoginEnum.STATUS_FAIL);
        }
        HttpSession session = request.getSession();
        session.setAttribute(SessionKey.USER_INFO.name(), loginInfo.getId());
        if (pid != 0) {
            int asd = billService.insertUserP(loginInfo.getId(), pid);
        }
        return new LoginExcution<LoginInfo>(loginInfo, LoginEnum.SUCCESS);
    }

    @ApiOperation(value = "后台固定登陆")
    @PostMapping(value = "/backstageLogin")
    @ResponseBody
    public LoginExcution<Void> backstageLogin(String userName, String password) {
        if (userName.equals("lingyingjiajiao") && password.equals("lingyingjiajiao")) {
            return new LoginExcution<Void>(null, LoginEnum.SUCCESS);
        } else {
            return new LoginExcution<Void>(null, LoginEnum.FAIL);
        }
    }


    @ApiOperation(value = "退出登录")
    @PostMapping(value = "/loginOut")
    @ResponseBody
    public LoginExcution<Void> loginOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return new LoginExcution<Void>(null, LoginEnum.OUTSUCCESS);
    }

    @ApiOperation(value = "获取OpenId")
    @PostMapping(value = "/getOpenId")
    @ResponseBody
    public LoginExcution<String> getOpenId(Integer userId) {
        String openId = loginService.getOpenId(userId);
        return new LoginExcution<String>(openId, LoginEnum.SUCCESS);
    }

    @ApiOperation(value = "新增认证表")
    @PostMapping(value = "/insertCertification")
    @ResponseBody
    public LoginExcution<Void> insertCertification(Integer userId) {
        int success = loginService.insertCertification(userId);
        if (success > 0) {
            return new LoginExcution<Void>(null, LoginEnum.SUCCESS);
        } else {
            return new LoginExcution<Void>(null, LoginEnum.FAIL);
        }
    }

    @ApiOperation(value = "注册用户")
    @PostMapping(value = "/registration")
    @ResponseBody
    public LoginExcution registration(String phone, String password, Integer type, Integer pid) {
        int count = loginService.registration(phone, MD5(password), type, pid);
        if (count == -1) {
            return new LoginExcution(null, LoginEnum.ISBEING);
        } else if (count == 0) {
            return new LoginExcution(null, LoginEnum.ADDFAIL);
        } else {
            return new LoginExcution(null, LoginEnum.ZSUCCESS);
        }
    }


    @ApiOperation(value = "忘记密码")
    @PostMapping(value = "/forgetPassword")
    @ResponseBody
    public LoginExcution<Void> forgetPassword(String phone, String password) {
        int count = loginService.updatePassword(phone, MD5(password));
        if (count > 0) {
            return new LoginExcution(null, LoginEnum.SETSUCCESS);
        } else {
            return new LoginExcution(null, LoginEnum.SETFAIL);
        }
    }


    @ApiOperation(value = "重置密码")
    @PostMapping(value = "/reSetPassword")
    @ResponseBody
    public LoginExcution<Void> reSetPassword(Integer userId, String password, String newPassword) {
        int count = loginService.reSetPassword(userId, MD5(password), MD5(newPassword));
        if (count > 0) {
            return new LoginExcution(null, LoginEnum.SETSUCCESS);
        } else {
            return new LoginExcution(null, LoginEnum.SETFAIL);
        }
    }

    @ApiOperation(value = "修改手机号")
    @PostMapping(value = "/setPhone")
    @ResponseBody
    public LoginExcution<Void> setPhone(String phone, String newPhone) {
        int count = loginService.setPhone(phone, newPhone);
        if (count == -1) {
            return new LoginExcution(null, LoginEnum.PHONEBEINGFAIL);
        } else if (count == 0) {
            return new LoginExcution(null, LoginEnum.SETFAIL);
        } else {
            return new LoginExcution(null, LoginEnum.SETSUCCESS);
        }
    }

    @ApiOperation(value = "定位地址插入")
    @PostMapping(value = "/insertLoginLocation")
    @ResponseBody
    public int insertLoginLocation(Integer userId,String latitude,String longitude,String address) {
        return loginService.insertLoginLocation(userId, latitude,longitude,address);
    }

    @ApiOperation(value = "MD5加密")
    @PostMapping(value = "/MD5")
    @ResponseBody
    public String md5() {
        return MD5(UUIDUtil.get32UUID());
    }

    /**
     * 对字符串md5加密(大写+数字)
     *
     * @param s 传入要加密的字符串
     * @return MD5加密后的字符串
     */

    public static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
